package com.cw.lang.common.framework.aspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.cw.lang.common.utils.IdGenerator;
import com.cw.lang.common.utils.StringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

@Aspect
@Component
public class WebLogAspect {

    private static final Logger log = LoggerFactory.getLogger(WebLogAspect.class);

    private final ObjectMapper mapper;
    //请求类名+方法名
    private String requestMethod;
    //请求id
    private String tradeId;
    @Autowired
    public WebLogAspect(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void requestLog() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void postLog() {
    }
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void getLog() {
    }
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PutMapping)")
    public void putLog() {
    }
    @Pointcut("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public void deleteLog() {
    }
    @Before("requestLog() || postLog() || getLog() || putLog() || deleteLog()")
    public void doBefore(JoinPoint joinPoint) {
        for (Object object : joinPoint.getArgs()) {
            if (object instanceof MultipartFile ||
                object instanceof HttpServletRequest ||
                object instanceof HttpServletResponse) {
                continue;
            }
            if(object == null){
                return;
            }
            tradeId = IdGenerator.nextStrId();
            requestMethod = joinPoint.getTarget().getClass().getSimpleName() +
                "." +
                joinPoint.getSignature().getName();
            if (log.isInfoEnabled()) {
                log.info(StringUtil.isBlank(requestMethod) ? "" : requestMethod + " : 交易ID：" + (StringUtil.isBlank(tradeId) ? "" : tradeId) + " 请求参数 : " + object.toString());
            }
        }
    }

    @AfterReturning(returning = "response", pointcut = "requestLog() || postLog()")
    public void doAfterReturning(Object response) throws Throwable {
        if (response != null) {
            log.info(StringUtil.isBlank(requestMethod) ? "" : requestMethod + " : 交易ID：" + (StringUtil.isBlank(tradeId) ? "" : tradeId) + " : 响应参数 : " + mapper.writeValueAsString(response));
        }
    }
}
